﻿using DH.Core.Helper;
using DH.Core.MapperHelper;
using DH.Data;
using DH.Data.ORM.EF;
using DH.Entity;
using DH.Service.ViewModels;
using Microsoft.Extensions.DependencyInjection;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DH.Service.Domain
{
   public class PrivilegeService: BaseService<PrivilegeEntity, string>
    {
        protected IServiceCollection _serviceCollection;
        
        public PrivilegeService(IServiceCollection service, DbCoreUnitOfWork unitOfWork) : base(service,unitOfWork)
        {
            this._serviceCollection = service;
            
        }

        public PrivilegeEntity Add(PrivilegeViewModel viewModel)
        {
            PrivilegeEntity model;
            model = DHMapper.Map<PrivilegeViewModel, PrivilegeEntity>(viewModel);
            model.CreatedOn = DateTimeOffset.Now;
            model.UpdatedOn = DateTimeOffset.Now;
            

            InsertSync(model);

            return model;


        }

        public bool Add(List<RoleFuncsDto> viewModels,string opUser,string subjectType,string objectType,bool hasResource)
        {
            

            var entitys = new List<PrivilegeEntity>();
            foreach (var vm in viewModels)
            {
                PrivilegeEntity model = new PrivilegeEntity();
                model.Id = Guid.NewGuid().ToString();
                model.SubjectId = vm.SubjectId;
                model.SubjectType = subjectType;
                model.ObjectType = objectType;
                model.ObjectId = vm.ObjectId;
                model.ResourceId = vm.ResourceId;
                model.CreatedOn = DateTimeOffset.Now;
                model.UpdatedOn = DateTimeOffset.Now;
                model.CreatedBy = opUser;
                model.UpdatedBy = opUser;
                model.SortIndex = 0;

                if (!string.IsNullOrEmpty(model.ObjectId))
                {
                    entitys.Add(model);
                }
                
            }

            _unitOfWork.ExecuteAndCommit(() => {

                if (viewModels.Any())
                {
                    var resourceId = viewModels.First().ResourceId;
                    var subjectId = viewModels.First().SubjectId;
                    var oldFuncs = GetByQuery(c=>c.SubjectId== subjectId).Where(c=>c.SubjectType== subjectType&&c.ObjectType==objectType);
                    if (hasResource)
                    {
                        oldFuncs = oldFuncs.Where(c=>c.ResourceId==resourceId);
                    }
                                       
                    _repository.Delete(oldFuncs);
                }
                if (entitys.Any()) {
                    _repository.Add(entitys);
                }
                
            });

            return true;

        }



        private bool DeleteOldFuncsForRole(string resourceId)
        {
            var oldFuncs = GetByQuery(c => c.SubjectType == PrivilegeTypeEnum.Role.ToString() && c.ResourceId== resourceId && c.ObjectType == PrivilegeTypeEnum.Function.ToString());

            _unitOfWork.ExecuteAndCommit(() =>
            {
                _repository.Delete(oldFuncs);
            });
            return true;
        }

        public List<PrivilegeViewModel> GetRolePrivilge(string roleId,string resourceId,string subjectType,string type)
        {
            var res = GetAllSync().Where(c=>c.SubjectType== subjectType && c.SubjectId==roleId);
            if (!string.IsNullOrEmpty(resourceId))
            {
                res = res.Where(c=>c.ResourceId==resourceId);
            }
            if (!string.IsNullOrEmpty(type))
            {
                res = res.Where(c=>c.ObjectType==type);
            }
            var  rolePrivileges= res.Select(c=> {
                return DHMapper.Map<PrivilegeEntity, PrivilegeViewModel>(c);
            }).ToList();

            return rolePrivileges;
        }

        /// <summary>
        /// 删除角色关联
        /// 1，删除角色权限
        /// 2，删除角色菜单
        /// 3，删除角色用户
        /// </summary>
        /// <param name="ids"></param>
        public void DeleteRolePrivilege(string[] ids)
        {
            var rolePrivileges = GetByQuery(c => ids.Contains(c.SubjectId) && c.SubjectType == PrivilegeTypeEnum.Role.ToString());

            DeleteSync(rolePrivileges);
        }

        public  void Delete(IEnumerable<PrivilegeEntity>  models)
        {
            _repository.Delete(models);
        }

        /// <summary>
        /// 删除菜单关联
        /// 1,删除角色菜单
        /// </summary>
        /// <param name="roleId"></param>
        public void DeleteMenuRelevance(string[] menuIds) {
            var menus = GetByQuery(c=>c.ObjectType==PrivilegeTypeEnum.Menu.ToString()&&menuIds.Contains(c.ObjectId));
            DeleteSync(menus);
        }
        public void DeleteRoleUsers(string roleId,string[] ids) {
            var roleUsers = GetByQuery(c => c.SubjectType == PrivilegeTypeEnum.Role.ToString() && c.SubjectId == roleId && c.ObjectType == PrivilegeTypeEnum.User.ToString() && ids.Contains(c.ObjectId));
            DeleteSync(roleUsers);
            
        }

        public string GetUserRoles(string userId)
        {
            var userRoles = "";
            var res = GetByQuery(c => c.SubjectType == PrivilegeTypeEnum.Role.ToString() && c.ObjectType == PrivilegeTypeEnum.User.ToString() && c.ObjectId == userId);
            foreach (var r in res)
            {
                userRoles += r.SubjectId + ",";
            }
            if (userRoles.Contains(","))
            {
                userRoles = userRoles.Substring(0, userRoles.Length - 1);
            }
            
            return userRoles;
        }
        
    }
}
